﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HmLab.Func1;

internal class LbLoadHualalaData {

  /// <summary>
  /// <see cref="Haimen.HuallDataLoader"/>
  /// </summary>
  public void Run() => RunImpl().Wait();

  async Task RunImpl() {
    string outPath = @"E:\work_etc\nina\2023haimen2\workshop_cs\haimen\data\数据源_新.xlsx";
    string dataDir = @"E:\work_etc\nina\2023haimen2\workshop_cs\haimen\data";
    DataGroupCfg[] groupAll = _groupCfgReader.Read(outPath);
    AppConfigRoot config = _appCfgReader.Read(groupAll, dataDir);

    string path = @"E:\work_etc\nina\2023haimen2\workshop_cslab\输O入test\W本周001.xlsx";
    DataRow[] dataList = await ReadDataRows(path, "W本周", config);

    var ColStr = (object col) => $"{col}:({col.GetType().Name})";
    foreach (var hehe in dataList) {
      Console.WriteLine(string.Join(", ", hehe.ColVal.Select(ColStr)));
    }
  }

  record DataRow(DataHeaderCfg[] Header, string GroupKey, object[] ColVal);
  async Task<DataRow[]> ReadDataRows(string path, string group, AppConfigRoot config) {
    DataHeaderCfg[] headerCfg = config.Header[group];
    string[] readCol = headerCfg
      .Where(h => h.Func != HeaderColFunc.VLOOKUP)
      .Where(h => h.Func != HeaderColFunc.COUNT)
      .Select(h => h.Name)
      .ToArray();

    LgExcelResult excelResult = await _excelReader.Read(path, 0, 3, 5, readCol);
    Dictionary<string, int> headerCol = excelResult.HeaderCol;

    int[] keyCol = headerCfg
      .Where(h => h.Func == HeaderColFunc.KEY)
      .Select(h => headerCol[h.Name])
      .ToArray();

    var GetCellVal = (DataHeaderCfg header, int col, LgExcelRow row) => {
      if (header.Func == HeaderColFunc.COUNT) {
        return 1;
      }

      object cell = row.ColVal[headerCol[header.Name]];
      if (header.Func == HeaderColFunc.VLOOKUP) {
        string key = (string)cell;
        return config.Lookup[key];
      }
      return cell;
    };

    var MakeRow = (LgExcelRow row) => {
      object[] colList = headerCfg
        .Select((h, c) => GetCellVal(h, c, row))
        .ToArray();

      string key = string.Join('_', keyCol
        .Select(c => row.ColVal[c])
        .ToArray());

      return new DataRow(headerCfg, key, colList);
    };

    LgExcelRow lastRow = excelResult.Rows[^1];
    bool lastRowHasData = !string.IsNullOrEmpty((string)lastRow.ColVal[1]);
    return (lastRowHasData ? excelResult.Rows : excelResult.Rows[..^1])
      .Select(MakeRow)
      .ToArray();
  }

  readonly LbReadResultConfig.GroupAll _groupCfgReader = new(new());
  readonly LbReadResultConfig.AppConfig _appCfgReader = new(new());

  readonly LbReadLargeExcel.Reader _excelReader = new(new());
}

record HuallMergeRow(object[] ColVal);
record HuallLoadResult(string Name, HuallMergeRow[] Rows);
